package fina2.dcs.mail.util;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Map;
import java.util.TreeMap;

import javax.mail.Authenticator;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Part;
import javax.mail.PasswordAuthentication;

import org.apache.log4j.Logger;

import fina2.dcs.mail.manager.MailUser;

public class MailUtil {
	private static Logger log = Logger.getLogger(MailUtil.class.getClass());

	public static Map<String, byte[]> getAttachments(Message message, MailUser mailUser) throws MessagingException, IOException {
		TreeMap<String, byte[]> map = new TreeMap<String, byte[]>();

		Object messageContentObject = message.getContent();

		if (messageContentObject instanceof String) {
			System.out.println("messageContentObject");
		}

		if (messageContentObject instanceof Multipart) {

			log.info(mailUser.getUser() + " : " + "Start Download.");
			long downloadDate = System.currentTimeMillis();

			Multipart multipartm = (Multipart) message.getContent();

			for (int i = 0; i < multipartm.getCount(); i++) {
				BodyPart bodyPart = multipartm.getBodyPart(i);
				if (!Part.ATTACHMENT.equalsIgnoreCase(bodyPart.getDisposition())) {
					continue;
				}
				BufferedInputStream bufferedInputStream = null;
				ByteArrayOutputStream byteArrayOutputStream = null;
				try {
					bufferedInputStream = new BufferedInputStream(bodyPart.getInputStream());
					byteArrayOutputStream = new ByteArrayOutputStream();

					byte[] contents = new byte[1024];
					while ((bufferedInputStream.read(contents)) != -1) {
						byteArrayOutputStream.write(contents);
					}
					byteArrayOutputStream.flush();
					map.put(bodyPart.getFileName(), byteArrayOutputStream.toByteArray());
				} finally {
					if (bufferedInputStream != null)
						bufferedInputStream.close();
					if (byteArrayOutputStream != null)
						byteArrayOutputStream.close();
				}
			}
			long date = System.currentTimeMillis() - downloadDate;
			log.info(mailUser.getUser() + " : " + "End Download.");
			log.info(mailUser.getUser() + " : " + "Download Time : " + date);
		} else {
			throw new MessagingException("Invalid Message Structure!");
		}
		return map;
	}

	public static String getProperty(String key, Map<String, String> properties) {
		String value = properties.get(key);

		if (value == null) {
			throw new RuntimeException("Properti [' " + key + "'] is NULL.");
		}
		if (value.trim().equals("")) {
			throw new RuntimeException("Invalid properti [' " + key + "'] valuse is ''.");
		}
		return value;
	}

	public static class MyAuthenticator extends Authenticator {
		private String user;
		private String password;

		public MyAuthenticator(String user, String password) {
			this.user = user;
			this.password = password;
		}

		public PasswordAuthentication getPasswordAuthentication() {
			return new PasswordAuthentication(user, password);
		}
	}

	public static String arrayToString(String[] a, String separator) {
		if (a == null || separator == null) {
			return null;
		}
		StringBuffer result = new StringBuffer();
		if (a.length > 0) {
			result.append(a[0]);
			for (int i = 1; i < a.length; i++) {
				result.append(separator);
				result.append(a[i]);
			}
		}
		return result.toString();
	}
}
